package embuzzled.g5;

import java.awt.Color;
import java.awt.Point;

public class Helper 
{
	/**
	 *  Creates a new copy of a boolean array.
	 * @param a A 2d boolean array
	 * @return A new copy of a.
	 */
	public static boolean[][] copyArray(boolean[][] a)
	{
		boolean[][] copy = new boolean[a.length][a[0].length];
		
		for(int i = 0; i < a.length; i++)
			for(int j = 0; j < a[0].length; j++)
				copy[i][j] = a[i][j];
		
		return copy;
	}
	
	/**
	 *  Creates a new copy of a Color array.
	 * @param a A 2d Color array
	 * @return A new copy of a.
	 */
	public static Color[][] copyArray(Color[][] a)
	{
		Color[][] copy = new Color[a.length][a[0].length];
		
		for(int i = 0; i < a.length; i++)
			for(int j = 0; j < a[0].length; j++)
				copy[i][j] = a[i][j];
		
		return copy;
	}
	
	/**
	 * Attempt to place color map "part" onto color map "whole" at point p.
	 * Returns the combined color map if possible, null if not.
	 * @param whole
	 * @param part
	 * @param p
	 * @return
	 */
	public static Color[][] superimpose(Color[][] whole, Color[][] part, Point p)
	{
		int x = p.x;
		int y = p.y;
		
		int localRows = part.length;
		int localCols = part[0].length;
		
		int xMax = p.x + localCols;
		int yMax = p.y + localRows;
		
		/*System.out.println("Adding a " +  localCols + "x" + localRows +
				" puzzle to a " + whole[0].length + "x" + whole.length +
				" map at location (" + x + ", " + y + ")");*/
		
		//Sanity check. Part would fall off the edge of whole.
		if(xMax > whole[0].length)
			return null;
		if(yMax > whole.length)
			return null;
		
		Color[][] newMap = new Color[whole.length][whole[0].length];
		
		for(int r = 0; r < localRows; r++)
			for(int c = 0; c < localCols; c++)
			{
				int wholeR = r + p.y;
				int wholeC = c + p.x;
				
				//System.out.println("Checking (" + wholeR + ", " + wholeC + ")");
				
				boolean isWholeClear = whole[wholeR][wholeC].equals(Constants.COLOR_CLEAR);
				boolean isPartClear = part[r][c].equals(Constants.COLOR_CLEAR);
				
				if(isPartClear)
				{
					//Not coloring this cell, keep old color.
					//System.out.println("Don't need to color");
					newMap[wholeR][wholeC] = whole[wholeR][wholeC];
				}
				else if(isWholeClear)
				{
					//Color in a previously clear cell.
					//System.out.println("Color in cell using " + part[r][c]);
					newMap[wholeR][wholeC] = part[r][c];
				}
				else if(!isWholeClear)
				{
					//Attempting to recolor an already colored cell.
					return null;
				}
			}
		
		//Copy the rest of the previous color map.
		for(int r = 0; r < newMap.length; r++)
			for(int c = 0; c < newMap[0].length; c++)
			{
				if(newMap[r][c] == null)
					newMap[r][c] = whole[r][c];
			}
		
		return newMap;
	}
}
